package com.hua.hiring.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;


/**
 * 单态登录
 *
 * @author  刘天印
 * @date  2018年12月11日下午4:33:30
 */
public class HttpSessionAttibutrListener implements HttpSessionAttributeListener {
	/**
	 * 1.登录时先检查Map里的string(对应的是帐号)是否有 有就把Session失效
	 * 2.session失效 把缓存在Map里的session清除
	 * 3.把新帐号关联到Map里
	 */
	public Map<String, HttpSession> loginInfoMap = new HashMap<>();
	
	/**
	 * 当session创建时会被调用
	 * session.setAttibute()
	 */
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent)  { 
    	
    	String  sessionAttibuteName = httpSessionBindingEvent.getName();
    	if("talentCode".equals(sessionAttibuteName) || "companyCode".equals(sessionAttibuteName)) {
    		//帐号
    		String SessionAttibuteValue = (String) httpSessionBindingEvent.getValue();
    		//先判断Map里是否有此帐号
    		HttpSession session = loginInfoMap.get(SessionAttibuteValue);
    		if(session != null) {
    			session.invalidate();
    		}
    		//把新帐号关联到Map里
    		loginInfoMap.put(SessionAttibuteValue, httpSessionBindingEvent.getSession());
    	}
    }
    /**
	 * 当session销毁时会被调用
	 * session.removen()
	 */
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent)  { 
    	
    	String  sessionAttibuteName = httpSessionBindingEvent.getName();
    	if("talentCode".equals(sessionAttibuteName) || "companyCode".equals(sessionAttibuteName)) {
    		//帐号
    		String SessionAttibuteValue = (String) httpSessionBindingEvent.getValue();
    		loginInfoMap.remove(SessionAttibuteValue);
    			
    	}
    }
    /**
	 * 当session更改时会被调用
	 * session.setAttibute()
	 */
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent)  { 
    }
	
}
